<?php
declare(strict_types=1);

namespace App\Services\Tools;

use App\Repositories\LogRepository;
use Symfony\Component\HttpClient\HttpClient;

class YlService
{
    private $url = 'https://papi.020leader.com/unipay/';

    private $payment;

    public function __construct(array $params = [])
    {
        $this->payment = $params;
    }

    // 发起支付
    public function pay(string $openId, string $orderNo, string $payAmt, string $title, string $desc, string $deviceIp, string $attach = "", string $clientType = "miniprogram", int $isMing = 1)
    {
        // $log = new LogRepository("pay-yl");
        // $log->log("payment", $this->payment);
        $param = [
            'service'     => 'pay.weixin.jspay',       //	String	是	接口类型,
            'version'     => '3.0',                    //	String	是	版本号：3.0',
            'merchantNum' => $this->payment["merchantNum"],        //	String	是	门店号',

            'subOpenid'        => $openId,                 //  String	是	支付用户id',
            'terminalUniqueNo' => $deviceIp,                 //	String	是	终端设备号，商户自定义，退款时需传入此参数',
            'inputFee'         => $payAmt,                   //	Double	是	收款金额，单位元（不允许包含任何字、符号，保留两位小数）',
            'orderNumExternal' => $orderNo,       //  String	否	商户系统内部的订单号，每次下单请求确保在商户系统唯一（32字符以内）',

            'transSubject'     => $title,       //  String	否	商户自定义商品标题',
            'remarks'          => $desc,       //  String	否	订单备注',
            'notifyUrl'  => $this->payment["notifyUrl"],       //  String	否	异步接收支付结果通知的回调地址，通知url必须为外网可访问的url，不能携带参数。 公网域名必须为https，如果是走专线接入，使用专线NAT IP或者私有回调域名可使用http',
            'clientType' => $clientType,       //  String	否	客户端类型：miniprogram、WEB、PC、IOS、ANDROID',
            'codeAttach' => $attach,       //  String	否	支付标记，支付成功，或者回调原样返回，对应attach字段',
            'isMing'     => $isMing,       //  String	否	1小程序支付，其他公众号支付',
            'subAppid'   => $this->payment["subAppid"], // 'wx15a6aa8982dbdb49',       //  String	否	填微信公众号支付的公众号id或微信小程序支付的小程序appid; 选填，如果传了会使用此appid 进行下单；没传使用商户进件时最新配置的 appid',
            'cashierNum' => 'autowx',       //  String	否	默认autoali,autowx',
        ];
        $param['sign'] = $this->sign($param);
        // $log->log("params", $this->payment);
        // $log->File();
        $httpClient = HttpClient::create();
        $response = $httpClient->request('POST', $this->url, ['body' => $param]);
        $content = $response->getContent(false);
        return $content;
    }


    // //签名
    public function sign(array $param): string
    {
        $key = $this->payment['key'];
        ksort($param);
        $http_build_query = http_build_query($param);
        $http_build_query .= '&key=' . $key;
        $http_build_query = urldecode($http_build_query);
        // echo $http_build_query . PHP_EOL;
        return strtoupper(md5($http_build_query));
    }




    public function verifySign(array $data,$sign)
    {
        unset($data["sign"]);
        return strtoupper($sign) == $this->sign($data);

        // $url = 'https://papi.020leader.com/unipay2/checkSign?';
        //
        // $client = HttpClient::create();
        // // $response = $client->request('POST', $url, [
        // //     'json' => $data
        // // ]);
        // $params = [
        //     "cashier_num" => $data["cashierNum"],
        //     "client_type" => "",
        //     "dynamic_id" => "",
        //     "external_num" => "",
        //     "service" => "",
        //     "terminal_unique_no" => "",
        //     "merchant_num" => $data["merchantNum"],
        //     "total_fee" => $data["inputFee"],
        //     "version" => "3.0",
        //     "key" => $key
        // ];
        // $url .= urldecode(http_build_query($params));
        //
        // $response = $client->request('POST', $url, []);
        // $content = $response->getContent();
        // $content = json_decode($content,true);
        //
        // if($content['result_code'] !== 'SUCCESS'){
        //     return false;
        // }
        // if(!isset($content['result_data']) || isset($content['result_data']['sign'])){
        //     return false;
        // }
        // return  $sign === $content['result_data']['sign'];

    }


}